package org.fisco.bcos.evidence.gateway.service;

import org.fisco.bcos.evidence.gateway.config.ResultCode;
import org.fisco.bcos.evidence.gateway.config.ResultJson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.fisco.bcos.evidence.gateway.entity.bcos.*;
import org.fisco.bcos.evidence.gateway.utils.Md5Algs;
import org.fisco.bcos.evidence.gateway.utils.http.HttpUtils;
import org.fisco.bcos.evidence.gateway.utils.json.JsonUtils;
import org.fisco.bcos.evidence.gateway.utils.string.StringUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@Service
public class EvidenceService {
    public final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${evidence.user.default.org}")
    private String defaultOrg;

    @Value("${evidence.user.default.platform}")
    private String defaultPlat;

    /// bcos accoun
    @Value("${bcos.account.add}")
    private String bcosAccountAddUrl; // 添加账户

    @Value("${bcos.account.get}")
    private String bcosAccountGetUrl; // 获取账户

    @Value("${bcos.account.check}")
    private String bcosAccountCheckUrl; // 检查账户，如果不存证则创建

    /// bcos evidence
    @Value("${bcos.evidence.add}")
    private String bcosEvidenceAddUrl; // 新创建存证上链

    @Value("${bcos.evidence.get}")
    private String bcosEvidenceGetUrl; // 根据key获取已经存证的数据

    @Value("${bcos.evidence.onwer}")
    private String bcosEvidenceOnwerUrl; // 根据owner所有人获取所有上链数据

//    bcos:
//    account:
//    add: http://39.103.152.46:8080/account/addAccount
//    get: http://39.103.152.46:8080/account/getAccount
//    check: http://39.103.152.46:8080/account/selectForUpdateAccount
//    evidence:
//    add: http://39.103.152.46:8080/evidence/addEvidence
//    get: http://39.103.152.46:8080/evidence/getEvidence
//    onwer: http://39.103.152.46:8080/evidence/getEvidencesByOwner
//


//
//    @Autowired
//    private FabricService fabricService;
//
//    @Resource
//    private EvidenceUserService evidenceUserService;
//
//    @Resource
//    private FabricUserService fabricUserService;
//
//    @Resource
//    private TextSecurityService textSecurityService;
//
//    @Resource
//    private TransactionRecordRepository transactionRecordRepository;
//
//    @Resource
//    private FabricTransactionRepository fabricTransactionRepository;
//
//    @Resource
//    private EvidenceInfoRepository evidenceInfoRepository;
//
//    @Resource
//    private ChainCodeRepository chainCodeRepository;

//    /**
//     * 存证接口1.0
//     *
//     * @param param
//     * @return
//     * @throws Exception
//     */
//    public String evidenceV1_0(EvidenceReq param) throws Exception {
//        // 获取用户基本信息
//        UserInfoReq userInfoReq = JsonUtils.jsonStr2Object(param.getUser(), UserInfoReq.class);
//
//        FabricUser orgAdminUser = fabricUserService.getFabricOrgAdminUser(defaultOrg);
//        if (orgAdminUser == null) {
//            logger.warn("Get org admin user failed for org:" + defaultOrg);
//            throw new Exception("Get org admin user failed for org:" + defaultOrg);
//        }
//
//        // 上链内容检测
//        String checkResult = textSecurityService.TextFilter(userInfoReq.getUserId(), param.getData());
//        if (StringUtils.isNotBlank(checkResult)) {
//            return checkResult;
//        }
//
//        // 数据存证
//        String key = param.getEvidenceId();
//        if (key == null || key.equals("")) {
//            key = UUID.randomUUID().toString();
//        }
//        String[] args = new String[]{JsonUtils.toJson(param), key};
//        InvokeResponse<String> res = (InvokeResponse) fabricService.invoke(orgAdminUser,
//                "evidence1_0", args, "invoke");
//        return res.getTransactionId();
//    }

    /**
     * 存证接口1.1
     *
     * @param param
     * @return
     * @throws Exception
     */
    public String evidence1_1(EvidenceReq param) throws Exception {
        String app = "";  /// Fabric bcplatform 源码继承
        if (StringUtils.isNotBlank(param.getUserPlatform())) {
            app = param.getUserPlatform();
        }
        param.setUserPlatform(defaultPlat);


        // 获取用户基本信息
        UserInfoReq userInfoReq = JsonUtils.jsonStr2Object(param.getUser(), UserInfoReq.class);
        if(userInfoReq == null || StringUtils.isBlank(userInfoReq.getUserId())){
            return ResultCode.BAD_REQUEST.getMsg(); /// 参数或语法有误
        }


        //BCOS
        // 1. 查看用户身份是否已经上链
        BcosAccount account = accountUpBcos(userInfoReq);
        if (account == null) {
            logger.error("Account up bcos failed, user_id" + userInfoReq.getUserId());
            return ResultCode.UpAccountBlockchainException.getMsg(); /// 账户上链失败
        }

        // 2. 构造区块链存证请求
        BcosEvidenceReq evidenceReq = new BcosEvidenceReq();
        evidenceReq.setType(param.getType());
        evidenceReq.setData(param.getData());
        evidenceReq.setOwner(account.getAccountHash());
        evidenceReq.setEvidenceId(param.getEvidenceId());
        evidenceReq.setDescription(param.getDescription());
        if (StringUtils.isNotBlank(app)) {
            evidenceReq.setApp(app);
        } else {
            evidenceReq.setApp(param.getUserPlatform());
        }

        //3. 存证上链
        BcosEvidence upEvidence = evidenceUpBcos(evidenceReq, account);
        if (upEvidence == null) {
            logger.error("Evidence up bcos failed, user_id" + evidenceReq.getEvidenceId());
            return ResultCode.UpEvidenceBlockchainException.getMsg(); /// 存证上链失败
        }
        return upEvidence.getEhash();


//
//
////
////        // 获取上链用户身份信息
////        FabricUser commUser = evidenceUserService.getEvidenceFabricUser(param.getUserPlatform(),
////                userInfoReq, defaultOrg);
////        if (null == commUser) {
////            throw new Exception("Not find user cert for " + userInfoReq.getUserId());
////        }
////
////        // 申请用户链上唯一身份
////        EvidenceUser evidenceUser = evidenceUserService.applyBcUserIdentify(param.getUserPlatform(),
////                userInfoReq, commUser);
////
////        // 上链内容检测
////        String checkResult = textSecurityService.TextFilter(commUser.getName(), param.getData());
////        if (StringUtils.isNotBlank(checkResult)) {
////            return checkResult;
////        }
//
//        // 构造区块链存证请求
//        FabricEvidenceReq evidenceReq = new FabricEvidenceReq();
//        evidenceReq.setType(param.getType());
//        evidenceReq.setData(param.getData());
//        evidenceReq.setOwner(evidenceUser.getUserAddress());
//        evidenceReq.setEvidenceId(param.getEvidenceId());
//        evidenceReq.setDescription(param.getDescription());
//        if (StringUtils.isNotBlank(app)) {
//            evidenceReq.setApp(app);
//        } else {
//            evidenceReq.setApp(param.getUserPlatform());
//        }
//
//        // 申请存证
//        String[] args = new String[]{JsonUtils.toJson(evidenceReq)};
//        InvokeResponse<String> res = (InvokeResponse) fabricService.invoke(commUser,
//                "evidence1_1", args, "invoke", app);
//        if (StringUtils.isBlank(res.getTransactionId())) {
//            logger.error("Evidence failed for " + param.getEvidenceId());
//            throw new Exception("Evidence failed for " + param.getEvidenceId());
//        }
//
////        // 保存存证信息
////        EvidenceInfo evidenceInfo = new EvidenceInfo();
////        evidenceInfo.setTxId(res.getTransactionId());
////        evidenceInfo.setType(evidenceReq.getType());
////        evidenceInfo.setOwner(evidenceReq.getOwner());
////        evidenceInfo.setEvidenceId(evidenceReq.getEvidenceId());
////        evidenceInfo.setDescription(evidenceReq.getDescription());
////        evidenceInfo = evidenceInfoRepository.save(evidenceInfo);
////
////        return res.getTransactionId();
    }

    /// BOCS 账户上链
    private BcosAccount accountUpBcos(UserInfoReq userInfoReq) {
        HttpUtils httpUtils = new HttpUtils();

        BcosAccount account = new BcosAccount();
        account.setId(userInfoReq.getUserId());
        account.setIdentity(userInfoReq.getIdentity());
        account.setName(userInfoReq.getName());
        account.setAccountType(userInfoReq.getAccountType());

        //账户上链
        String conResult = httpUtils.sendJsonPost("BCOS: 用户信息上链", bcosAccountCheckUrl, JsonUtils.beanToMap(account));
        logger.info("BCOS: 用户信息上链请求结果：" + conResult);
        try {
            JSONObject obj = JSON.parseObject(conResult);
            String code = obj.getString("code");
            if ("200".equals(code)) {
                String data = obj.getString("data");
                System.out.println("data=" + data);

                if (StringUtils.isBlank(data)) {
                    return null;
                }

                account = JSONObject.parseObject(data, BcosAccount.class);
                return account;
            }
        } catch (Exception e) {
            logger.error("账户信息上链,解析区块链返回内容失败：", e);
        }
        return null;
    }

    private BcosEvidence evidenceUpBcos(BcosEvidenceReq evidenceReq, BcosAccount account) {
        BcosEvidence evidence = new BcosEvidence();
        evidence.setKey(evidenceReq.getEvidenceId());
        evidence.setOwner(account.getAccountHash()); // 注意: 拥有者使用账户hash
        evidence.setData(JsonUtils.toJson(evidenceReq)); /// 整体evidence数据取hash

        HttpUtils httpUtils = new HttpUtils();

        //账户上链
        String conResult = httpUtils.sendJsonPost("BCOS: 存证信息上链", bcosEvidenceAddUrl, JsonUtils.beanToMap(evidence));
        logger.info("BCOS: 用户信息上链请求结果：" + conResult);
        try {
            JSONObject obj = JSON.parseObject(conResult);
            String code = obj.getString("code");
            if ("200".equals(code)) {
                String data = obj.getString("data");
                System.out.println("data=" + data);

                if (StringUtils.isBlank(data)) {
                    return null;
                }

                evidence = JSONObject.parseObject(data, BcosEvidence.class);
                return evidence;
            }
        } catch (Exception e) {
            logger.error("存证信息上链,解析区块链返回内容失败：", e);
        }
        return null;
    }


    /**
     * 带文件信息存证接口1.1
     *
     * @param userPlatform user
     *                     evidenceId
     *                     description
     *                     data
     *                     file
     * @return
     * @throws Exception
     */
    public String evidenceWithFile1_1(String userPlatform,
                                      String user,
                                      String evidenceId,
                                      String description,
                                      String data,
                                      MultipartFile file) throws Exception {
        if (StringUtils.isBlank(userPlatform)) {
            userPlatform = defaultPlat;
        }

        // 获取用户基本信息
        UserInfoReq userInfoReq = JsonUtils.jsonStr2Object(user, UserInfoReq.class);
        if(userInfoReq == null || StringUtils.isBlank(userInfoReq.getUserId())){
            return ResultCode.BAD_REQUEST.getMsg(); /// 参数或语法有误
        }

        // 获取数据基本信息
        FileInfoReq fileInfoReq = JsonUtils.jsonStr2Object(data, FileInfoReq.class);

        // 计算文件hash
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(file.getInputStream(), baos);
        String digest = Md5Algs.getMD5(baos.toByteArray());
        fileInfoReq.setHash(digest);


        //BCOS
        // 1. 查看用户身份是否已经上链
        BcosAccount account = accountUpBcos(userInfoReq);
        if (account == null) {
            logger.error("Account up bcos failed, user_id" + userInfoReq.getUserId());
            return ResultCode.UpAccountBlockchainException.getMsg(); /// 账户上链失败
        }

        // 2. 构造区块链存证请求
        BcosEvidenceReq evidenceReq = new BcosEvidenceReq();
        evidenceReq.setType("file");
        evidenceReq.setData(JsonUtils.toJson(fileInfoReq)); /// 上传的文件作为Data字段
        evidenceReq.setOwner(account.getAccountHash());
        evidenceReq.setEvidenceId(evidenceId);
        evidenceReq.setDescription(description);
        evidenceReq.setApp(userPlatform);

        //3. 存证上链
        BcosEvidence upEvidence = evidenceUpBcos(evidenceReq, account);
        if (upEvidence == null) {
            logger.error("Evidence up bcos failed, user_id" + evidenceReq.getEvidenceId());
            return ResultCode.UpEvidenceBlockchainException.getMsg(); /// 存证上链失败
        }
        return upEvidence.getEhash();



//
//        // 获取上链用户身份信息
//        FabricUser commUser = evidenceUserService.getEvidenceFabricUser(userPlatform,
//                userInfoReq, defaultOrg);
//        if (null == commUser) {
//            throw new Exception("Not find user cert for " + userInfoReq.getUserId());
//        }
//
//        // 申请用户链上唯一身份
//        EvidenceUser evidenceUser = evidenceUserService.applyBcUserIdentify(userPlatform,
//                userInfoReq, commUser);
//
//        // 上链内容检测
//        String checkResult = textSecurityService.TextFilter(commUser.getName(), data);
//        if (StringUtils.isNotBlank(checkResult)) {
//            return checkResult;
//        }
//
//        // 构造区块链存证请求
//        FabricEvidenceReq evidenceReq = new FabricEvidenceReq();
//        evidenceReq.setType("file");
//        evidenceReq.setData(JsonUtils.toJson(fileInfoReq));
//        evidenceReq.setOwner(evidenceUser.getUserAddress());
//        evidenceReq.setEvidenceId(evidenceId);
//        evidenceReq.setDescription(description);
//        evidenceReq.setApp(userPlatform);
//
//
//        // 申请存证
//        String[] args = new String[]{JsonUtils.toJson(evidenceReq)};
//        InvokeResponse<String> res = (InvokeResponse) fabricService.invoke(commUser,
//                "evidence1_1", args, "invoke");
//        if (StringUtils.isBlank(res.getTransactionId())) {
//            logger.error("Evidence failed for " + evidenceId);
//            throw new Exception("Evidence failed for " + evidenceId);
//        }
//
//        // 保存存证信息
//        EvidenceInfo evidenceInfo = new EvidenceInfo();
//        evidenceInfo.setTxId(res.getTransactionId());
//        evidenceInfo.setType(evidenceReq.getType());
//        evidenceInfo.setOwner(evidenceReq.getOwner());
//        evidenceInfo.setEvidenceId(evidenceReq.getEvidenceId());
//        evidenceInfo.setDescription(evidenceReq.getDescription());
//        evidenceInfo = evidenceInfoRepository.save(evidenceInfo);
//
//        return res.getTransactionId();
    }

//    /**
//     * 通过交易id查询
//     * TODO: 目前我们不允许chaincode重名，即使在不同的channel也不允许
//     * @param txId
//     * @return
//     * @throws Exception
//     */
//    public Object queryByTxId(String txId) throws Exception {
//        TransactionRecord transactionRecord = transactionRecordRepository.findByTransactionId(txId);
//        String chaincodeName = "";
//        if (transactionRecord == null) {
//            // 查询本地
//            FabricTransaction fabricTransaction = fabricTransactionRepository.findByTxHash(txId);
//            if (fabricTransaction == null) {
//                throw new Exception("queryByTxId错误，请联系区块链管理员！");
//            } else {
//                chaincodeName = fabricTransaction.getChaincodename();
//            }
//        } else {
//            chaincodeName = transactionRecord.getChainCodeName();
//        }
//        List<ChainCode> chaincodes = chainCodeRepository.findByChaincodeName(chaincodeName);
//        if (chaincodes.isEmpty()) {
//            throw new Exception("没有找到chaincode！");
//        }
//        FabricUser admin = fabricUserService.getFabricOrgAdminUser(defaultOrg);
//        return fabricService.invoke(admin, chaincodes.get(0), txId);
//    }

//    /**
//     * @return java.lang.Object
//     * @Author wx
//     * @Description 根据存证id查询历史交易记录
//     * @Date 15:58 2021/1/23
//     * @Param [evidenceId]
//     **/
//    public Object queryHistoryForKey(EvidenceHistoryQueryReq param) throws Exception {
//        logger.info("queryHistoryForKey defaultOrg="+defaultOrg);
//        // 获取上链用户身份信息
//        FabricUser adminUser = fabricUserService.getFabricOrgAdminUser(defaultOrg);
//        if(adminUser != null){
//            logger.info("queryHistoryForKey adminUser="+adminUser);
//        }
//        String app = "";
//        if (StringUtils.isNotBlank(param.getUserPlatform())) {
//            app = param.getUserPlatform();
//        }
//        param.setUserPlatform(defaultPlat);
//        //param.setUserPlatform("evidence");//zuo test
//        String[] args = new String[]{param.getUserPlatform(), param.getEvidenceId()};
//
//        logger.info("queryHistoryForKey args[], getUserPlatform="+param.getUserPlatform()+ ",getEvidenceId="+param.getEvidenceId());
//        logger.info("app="+app);
//
//        String fabricResp = (String) fabricService.invoke(adminUser, "queryHistoryForKey", args, "query", app);
//        if (StringUtils.isBlank(fabricResp)) {
//            logger.warn("Query history log failed for [" + param.getUserPlatform() + ":" + param.getEvidenceId() + "]");
//            throw new Exception("Query history log failed for [" + param.getUserPlatform() + ":" + param.getEvidenceId() + "]");
//        }
//        List<FabricHistoryData> historyDataList = JsonUtils.convertJson2List(fabricResp, FabricHistoryData.class);
//        EvidenceHistoryResp resp = buildHistoryDataResp(historyDataList);
//        logger.info("resp="+resp.toString());
//        return resp;
//    }

    /**
     * //     * @return java.lang.Object
     * //     * @Author wx
     * //     * @Description 根据存证id查询历史交易记录
     * //     * @Date 15:58 2021/1/23
     * //     * @Param [evidenceId]
     * //
     **/
    public BcosEvidence queryHistoryForKey(String evidenceId) throws Exception {
        HttpUtils httpUtils = new HttpUtils();

        //账户上链
//        Map<String, Object> paramMap = new HashMap<String, Object>();
//        paramMap.put("key", evidenceId); /// 上链的key是证据ID, 注意
        String getParam = "key="+evidenceId;

        //todo get
        String conResult = httpUtils.sendGet(bcosEvidenceGetUrl, evidenceId);
        logger.info("BCOS: 存证信息查询请求结果：" + conResult);
        try {
            JSONObject obj = JSON.parseObject(conResult);
            String code = obj.getString("code");
            if ("200".equals(code)) {
                String data = obj.getString("data");
                System.out.println("data=" + data);

                if (StringUtils.isBlank(data)) {
                    return null;
                }

                BcosEvidence evidence = JSONObject.parseObject(data, BcosEvidence.class);
                return evidence;
            }
        } catch (Exception e) {
            logger.error("存证信息查询请求结果,解析区块链返回内容失败：", e);
        }
        return null;

//
//        /////
//
//        logger.info("queryHistoryForKey defaultOrg="+defaultOrg);
//        // 获取上链用户身份信息
//        FabricUser adminUser = fabricUserService.getFabricOrgAdminUser(defaultOrg);
//        if(adminUser != null){
//            logger.info("queryHistoryForKey adminUser="+adminUser);
//        }
//        String app = "";
//        if (StringUtils.isNotBlank(param.getUserPlatform())) {
//            app = param.getUserPlatform();
//        }
//        param.setUserPlatform(defaultPlat);
//        //param.setUserPlatform("evidence");//zuo test
//        String[] args = new String[]{param.getUserPlatform(), param.getEvidenceId()};
//
//        logger.info("queryHistoryForKey args[], getUserPlatform="+param.getUserPlatform()+ ",getEvidenceId="+param.getEvidenceId());
//        logger.info("app="+app);
//
//        String fabricResp = (String) fabricService.invoke(adminUser, "queryHistoryForKey", args, "query", app);
//        if (StringUtils.isBlank(fabricResp)) {
//            logger.warn("Query history log failed for [" + param.getUserPlatform() + ":" + param.getEvidenceId() + "]");
//            throw new Exception("Query history log failed for [" + param.getUserPlatform() + ":" + param.getEvidenceId() + "]");
//        }
//        List<FabricHistoryData> historyDataList = JsonUtils.convertJson2List(fabricResp, FabricHistoryData.class);
//        EvidenceHistoryResp resp = buildHistoryDataResp(historyDataList);
//        logger.info("resp="+resp.toString());
//        return resp;
    }

//    /**
//     * @return java.lang.Object
//     * @Author wx
//     * @Description 查询用户存证分页信息
//     * @Date 8:50 2021/2/2
//     * @Param [param]
//     **/
//    public Object queryEvidenceByUser(UserEvidenceQueryReq param) throws Exception {
//        UserEvidenceQueryResp resp = new UserEvidenceQueryResp();
//        String app = "";
//        if (StringUtils.isNotBlank(param.getUserPlatform())) {
//            app = param.getUserPlatform();
//        }
//        param.setUserPlatform(defaultPlat);
//
//        // 获取用户基本信息
//        UserInfoReq userInfoReq = JsonUtils.jsonStr2Object(param.getUser(), UserInfoReq.class);
//        if (null == userInfoReq) {
//            logger.error("Illegal user info:" + param.getUser());
//            throw new Exception("Illegal user info:" + param.getUser());
//        }
//
//        EvidenceUser evidenceUser = evidenceUserService.getEvidenceUser(param.getUserPlatform(),
//                userInfoReq, defaultOrg);
//        if (null == evidenceUser) {
//            logger.error("Not find user:" + userInfoReq.getUserId());
//            throw new Exception("Not find user:" + userInfoReq.getUserId());
//        }
//
//        // 获取上链用户身份信息
//        FabricUser commUser = evidenceUserService.getEvidenceFabricUser(param.getUserPlatform(),
//                userInfoReq, defaultOrg);
//        if (null == commUser) {
//            throw new Exception("Not find user cert for " + userInfoReq.getUserId());
//        }
//
//        // 构造存证查询请求
//        FabricUserEvidenceQueryReq userEvidenceQueryReq = new FabricUserEvidenceQueryReq();
//        userEvidenceQueryReq.setOwner(evidenceUser.getUserAddress());
//        userEvidenceQueryReq.setStartTxId(param.getStartTxId());
//        userEvidenceQueryReq.setPageSize(param.getPageSize());
//
//        // 查询存证信息
//        String[] args = new String[]{JsonUtils.toJson(userEvidenceQueryReq)};
//        String fabricResp = (String) fabricService.invoke(commUser, "queryEvidenceByUser", args, "query", app);
//        if (StringUtils.isBlank(fabricResp)) {
//            logger.error("Query evidence failed for " + userInfoReq.getUserId());
//            throw new Exception("Query evidence failed for " + userInfoReq.getUserId());
//        }
//        FabricUserEvidenceQueryResp evidenceQueryResp = JsonUtils.jsonStr2Object(fabricResp, FabricUserEvidenceQueryResp.class);
//        for (String keyData : evidenceQueryResp.getData()) {
//            List<FabricHistoryData> historyDataList = JsonUtils.convertJson2List(keyData, FabricHistoryData.class);
//            EvidenceHistoryResp oneResp = buildHistoryDataResp(historyDataList);
//            resp.addHistoryData(oneResp);
//        }
//        if (null != evidenceQueryResp.getStartTxId()) {
//            resp.setStartTxId(evidenceQueryResp.getStartTxId());
//        }
//        if (null != evidenceQueryResp.getCount()) {
//            resp.setCount(evidenceQueryResp.getCount());
//        }
//
//        return resp;
//    }


    /**
     * @return java.lang.Object
     * @Author wx
     * @Description 查询用户存证信息
     * @Date 8:50 2021/2/2
     * @Param [param]
     **/
    public String queryEvidenceByUser(String userId) throws Exception {

        HttpUtils httpUtils = new HttpUtils();

        //1. 账户查询
        BcosAccount account = null;
//        Map<String, Object> paramMap = new HashMap<String, Object>();
//        paramMap.put("id", userId);
        String getParam = "id="+userId;

        /// todo get
        String conResult = httpUtils.sendGet(bcosAccountGetUrl, getParam);
        logger.info("BCOS: 用户信息查询请求结果：" + conResult);
        try {
            JSONObject obj = JSON.parseObject(conResult);
            String code = obj.getString("code");
            if ("200".equals(code)) {
                String data = obj.getString("data");
                System.out.println("data=" + data);

                if (StringUtils.isBlank(data)) {
                    logger.info("无此用户的存证信息：");
                    return null;
                }

                account = JSONObject.parseObject(data, BcosAccount.class);
            }
        } catch (Exception e) {
            logger.error("用户信息查询请求结果,解析区块链返回内容失败：", e);
            return null;
        }


        ///2. 账户所有存证信息查询
        String owner = account.getAccountHash();
//        paramMap = new HashMap<String, Object>();
//        paramMap.put("owner", owner);
        getParam = "owner="+owner;

        // todo get
        conResult = httpUtils.sendGet(bcosEvidenceOnwerUrl, getParam);
        logger.info("BCOS: 用户所有上链存证信息查询：" + conResult);
        try {
            JSONObject obj = JSON.parseObject(conResult);
            String code = obj.getString("code");
            if ("200".equals(code)) {
                String data = obj.getString("data");
                System.out.println("data=" + data);

                if (StringUtils.isBlank(data)) {
                    logger.error("查询上链存证异常.");
                    return null;
                }

                return data;
                //account = JSONObject.parseObject(data, BcosAccount.class);
            }
        } catch (Exception e) {
            logger.info("用户信息查询请求结果,解析区块链返回内容失败：", e);
            return null;
        }
        return null;
    }


//    /**
//     * @return java.lang.Object
//     * @Author wx
//     * @Description 查询最新存证记录信息
//     * @Date 17:07 2021/2/5
//     * @Param [param]
//     **/
//    public Object queryEvidenceRecords(EvidenceRecordsQueryReq param) {
//        List<EvidenceRecordResp> recordRespList = new ArrayList<>();
//        List<EvidenceInfo> evidenceInfoList = evidenceInfoRepository.getLatestRecords(Integer.parseInt(param.getQueryAmount()));
//        for (EvidenceInfo one : evidenceInfoList) {
//            EvidenceRecordResp resp = new EvidenceRecordResp();
//            resp.setTxId(one.getTxId());
//            resp.setType(one.getType());
//            resp.setDesc(one.getDescription());
//            resp.setEvidenceTime(DateUtil.sdf.format(one.getCreateTime()));
//            recordRespList.add(resp);
//        }
//        return recordRespList;
//    }

//    /**
//     * @return java.lang.Object
//     * @Author wx
//     * @Description 获取存证数量相关信息
//     * @Date 17:18 2021/2/5
//     * @Param []
//     **/
//    public Object queryEvidenceAmount() throws Exception {
//        EvidenceAmountResp resp = new EvidenceAmountResp();
//        // 获取存证数量
//        Long evidenceAmount = evidenceInfoRepository.getEvidenceAmount();
//
//        // 获取区块高度
//        // 获取上链用户身份信息
//        FabricUser adminUser = fabricUserService.getFabricOrgAdminUser(defaultOrg);
//        Long blockHeight = fabricService.queryBlockHeight(adminUser);
//
//        resp.setEvidenceAmount(String.valueOf(evidenceAmount));
//        resp.setBlockHeight(String.valueOf(blockHeight));
//        return resp;
//    }

//    /**
//     * @return org.fisco.bcos.evidence.gateway.response.EvidenceHistoryResp
//     * @Author wx
//     * @Description 构造存证历史记录
//     * @Date 16:13 2021/2/5
//     * @Param [historyDataList]
//     **/
//    private EvidenceHistoryResp buildHistoryDataResp(List<FabricHistoryData> historyDataList) {
//        EvidenceHistoryResp oneResp = new EvidenceHistoryResp();
//        long startTime = 0L;
//        long latestTime = 0L;
//        String evidenceId = null;
//        String desc = null;
//        for (FabricHistoryData oneHistoryData : historyDataList) {
//            if (StringUtils.isBlank(evidenceId)) {
//                evidenceId = oneHistoryData.getValue().getEvidenceId();
//            }
//            if (StringUtils.isBlank(desc)) {
//                desc = oneHistoryData.getValue().getDescription();
//            }
//
//            Date txDate = DateUtil.convertStrToDate(oneHistoryData.getDate());
//            if (null != txDate) {
//                Long txTime = DateUtil.convertStrToDate(oneHistoryData.getDate()).getTime();
//                if (startTime == 0) {
//                    startTime = txTime;
//                } else if (txTime < startTime) {
//                    startTime = txTime;
//                }
//                if (latestTime == 0) {
//                    latestTime = txTime;
//                } else if (txTime > latestTime) {
//                    latestTime = txTime;
//                }
//            }
//
//            EvidenceHistoryResp.EvidenceInfo evidenceInfo = new EvidenceHistoryResp.EvidenceInfo();
//            evidenceInfo.setTxId(oneHistoryData.getTxId());
//            evidenceInfo.setDate(oneHistoryData.getDate());
//            evidenceInfo.setType(oneHistoryData.getValue().getType());
//            evidenceInfo.setData(oneHistoryData.getValue().getData());
//            evidenceInfo.setDescription(oneHistoryData.getValue().getDescription());
//            oneResp.getHistoryData().add(evidenceInfo);
//        }
//        oneResp.setEvidenceId(evidenceId);
//        oneResp.setDescription(desc);
//        oneResp.setStartDate(DateUtil.convertTimeStampToStr(startTime));
//        oneResp.setLatestDate(DateUtil.convertTimeStampToStr(latestTime));
//
//        return oneResp;
//    }
}
